<template>
  <div>
    <!-- 目标区域 -->
    <div ref="targetRef" class="content-box">
      <div class="custom-content">
        <h1>Vue 3 图片生成示例</h1>
        <p>当前时间：{{ new Date().toLocaleString() }}</p>
        <div class="qrcode">📊 这里是图表/二维码等</div>
      </div>
    </div>
    <!-- 操作按钮 -->
    <button @click="generateImage">生成预览图</button>
    <!-- 图片预览 -->
    <Image
      :src="imageUrl"
      :width="200"
      :preview="{ visible,
        onVisibleChange: (vis) => {
          visible = vis; // 关键：同步更新 visible 状态
        }
       }"
      @close="onPreviewClose"
    />
  </div>
</template>

<script setup>
import { nextTick, ref } from "vue";
import { Image } from "ant-design-vue";
import html2canvas from "html2canvas";

const targetRef = ref(null);
const imageUrl = ref("");
const visible = ref(false);
const setVisible = (value) => {
  console.log('Preview closed');
  visible.value = value;
};
const generateImage = async () => {
  if (!targetRef.value) return;

  try {
    // 生成 canvas
    const canvas = await html2canvas(targetRef.value, {
      backgroundColor: "#ffffff", // 解决透明背景问题
      scale: 2, // 提高清晰度（2倍）
      useCORS: true, // 允许跨域图片
    });

    // 转换为图片 URL
    imageUrl.value = canvas.toDataURL("image/png");
    console.log("imageUrl", imageUrl);
    nextTick(() => { 
      visible.value = true;    
    });

  } catch (error) {
    console.error("生成图片失败:", error);
  }
};
// 新增：处理预览关闭事件
const onPreviewClose = () => {
  visible.value = false;
};
</script>

<style scoped>
.content-box {
  border: 1px solid #eee;
  padding: 20px;
  display: inline-block; /* 避免内容撑满屏幕 */
}
.preview {
  margin-top: 20px;
}
.preview img {
  max-width: 100%;
  border: 1px solid #ccc;
}
.custom-content {
  font-family: "Microsoft YaHei";
  color: #333;
}
.qrcode {
  margin-top: 10px;
  padding: 15px;
  background: #f0f8ff;
  display: inline-block;
}
</style>
